import React, { useState, useEffect } from 'react';
import {
  SafeAreaView,
  StatusBar,
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  FlatList,
  TextInput,
  ScrollView,
  Alert,
  ActivityIndicator,
} from 'react-native';

import DlnaPlayer, {
  Device,
  PlaybackStatus,
  DlnaPlayerEventType,
} from 'react-native-dlna-player';

const App = () => {
  const [devices, setDevices] = useState<Device[]>([]);
  const [connected, setConnected] = useState(false);
  const [connectedDevice, setConnectedDevice] = useState<Device | null>(null);
  const [videoUrl, setVideoUrl] = useState(
    'https://sample-videos.com/video123/mp4/720/big_buck_bunny_720p_1mb.mp4'
  );
  const [videoTitle, setVideoTitle] = useState('示例视频');
  const [playbackStatus, setPlaybackStatus] = useState<PlaybackStatus | null>(
    null
  );
  const [isSearching, setIsSearching] = useState(false);
  const [volume, setVolume] = useState(50);
  const [errorMessage, setErrorMessage] = useState('');

  // 权限检查
  useEffect(() => {
    const checkPermissions = async () => {
      try {
        const permissionResult = await DlnaPlayer.checkPermissions();
        if (!permissionResult.allGranted) {
          const granted = await DlnaPlayer.requestPermissions();
          if (!granted) {
            setErrorMessage('需要权限才能使用DLNA功能');
          }
        }
      } catch (error) {
        setErrorMessage(
          '权限检查失败：' +
            (error instanceof Error ? error.message : String(error))
        );
      }
    };

    checkPermissions();
  }, []);

  // 设置事件监听
  useEffect(() => {
    const deviceFoundSubscription = DlnaPlayer.addEventListener(
      DlnaPlayerEventType.DEVICE_FOUND,
      (device: Device) => {
        setDevices((prevDevices) => {
          const exists = prevDevices.some((d) => d.id === device.id);
          if (!exists) {
            return [...prevDevices, device];
          }
          return prevDevices;
        });
      }
    );

    const playbackStatusSubscription = DlnaPlayer.addEventListener(
      DlnaPlayerEventType.PLAYBACK_STATUS_CHANGED,
      (status: PlaybackStatus) => {
        setPlaybackStatus(status);
      }
    );

    const connectionStatusSubscription = DlnaPlayer.addEventListener(
      DlnaPlayerEventType.CONNECTION_STATUS_CHANGED,
      (status: boolean) => {
        setConnected(status);
        if (!status) {
          setConnectedDevice(null);
        }
      }
    );

    const errorSubscription = DlnaPlayer.addEventListener(
      DlnaPlayerEventType.ERROR,
      (error: Error) => {
        setErrorMessage(error.message);
        Alert.alert('错误', error.message);
      }
    );

    // 清理监听器
    return () => {
      DlnaPlayer.removeEventListener(deviceFoundSubscription);
      DlnaPlayer.removeEventListener(playbackStatusSubscription);
      DlnaPlayer.removeEventListener(connectionStatusSubscription);
      DlnaPlayer.removeEventListener(errorSubscription);
    };
  }, []);

  // 搜索设备
  const handleSearchDevices = async () => {
    try {
      setIsSearching(true);
      setErrorMessage('');
      setDevices([]);
      const foundDevices = await DlnaPlayer.searchDevices();
      setDevices(foundDevices);
    } catch (error) {
      setErrorMessage(
        '搜索设备失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    } finally {
      setIsSearching(false);
    }
  };

  // 连接设备
  const handleConnectDevice = async (deviceId: string) => {
    try {
      setErrorMessage('');
      const result = await DlnaPlayer.connectToDevice(deviceId);
      if (result) {
        const device = devices.find((d) => d.id === deviceId) || null;
        setConnectedDevice(device);
        setConnected(true);
        Alert.alert('成功', `已连接到设备：${device?.name || deviceId}`);
      } else {
        Alert.alert('连接失败', '无法连接到设备');
      }
    } catch (error) {
      setErrorMessage(
        '连接设备失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 断开设备连接
  const handleDisconnectDevice = async () => {
    try {
      setErrorMessage('');
      const result = await DlnaPlayer.disconnectFromDevice();
      if (result) {
        setConnected(false);
        setConnectedDevice(null);
        Alert.alert('成功', '已断开设备连接');
      } else {
        Alert.alert('断开失败', '无法断开设备连接');
      }
    } catch (error) {
      setErrorMessage(
        '断开设备失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 播放视频
  const handlePlayVideo = async () => {
    if (!connected) {
      Alert.alert('错误', '请先连接设备');
      return;
    }

    try {
      setErrorMessage('');
      const result = await DlnaPlayer.playVideo(videoUrl, videoTitle);
      if (!result) {
        Alert.alert('播放失败', '无法播放视频');
      }
    } catch (error) {
      setErrorMessage(
        '播放视频失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 暂停视频
  const handlePauseVideo = async () => {
    try {
      setErrorMessage('');
      await DlnaPlayer.pauseVideo();
    } catch (error) {
      setErrorMessage(
        '暂停视频失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 恢复播放
  const handleResumeVideo = async () => {
    try {
      setErrorMessage('');
      await DlnaPlayer.resumeVideo();
    } catch (error) {
      setErrorMessage(
        '恢复播放失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 停止播放
  const handleStopVideo = async () => {
    try {
      setErrorMessage('');
      await DlnaPlayer.stopVideo();
    } catch (error) {
      setErrorMessage(
        '停止视频失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 获取播放状态
  const handleGetStatus = async () => {
    try {
      setErrorMessage('');
      const status = await DlnaPlayer.getPlaybackStatus();
      setPlaybackStatus(status);
    } catch (error) {
      setErrorMessage(
        '获取状态失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 跳转到指定位置
  const handleSeek = async (seconds: number) => {
    try {
      setErrorMessage('');
      await DlnaPlayer.seekTo(seconds);
    } catch (error) {
      setErrorMessage(
        '跳转失败：' + (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 设置音量
  const handleSetVolume = async (value: number) => {
    try {
      setErrorMessage('');
      setVolume(value);
      await DlnaPlayer.setVolume(value);
    } catch (error) {
      setErrorMessage(
        '设置音量失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 静音/取消静音
  const handleToggleMute = async (mute: boolean) => {
    try {
      setErrorMessage('');
      await DlnaPlayer.setMute(mute);
    } catch (error) {
      setErrorMessage(
        '设置静音失败：' +
          (error instanceof Error ? error.message : String(error))
      );
    }
  };

  // 渲染设备列表项
  const renderDeviceItem = ({ item }: { item: Device }) => (
    <TouchableOpacity
      style={styles.deviceItem}
      onPress = { () => handleConnectDevice(item.id) }
    >
      <Text style={styles.deviceName}>{item.name}</Text>
      <Text style={styles.deviceInfo}>IP: {item.ip}</Text>
      <Text style={styles.deviceInfo}>ID: {item.id}</Text>
    </TouchableOpacity>
  );

  return (
    <SafeAreaView style={styles.container}>
      <StatusBar barStyle="dark-content" />
      <ScrollView contentContainerStyle={styles.scrollView}>
        <Text style={styles.title}>DLNA 播放器示例</Text>

        {errorMessage ? (
          <View style={styles.errorContainer}>
            <Text style={styles.errorText}>{errorMessage}</Text>
          </View>
        ) : null}

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>设备管理</Text>
          <TouchableOpacity
            style={styles.button}
            onPress={handleSearchDevices}
            disabled={isSearching}
          >
            <Text style={styles.buttonText}>
              {isSearching ? '正在搜索...' : '搜索设备'}
            </Text>
            {isSearching && (
              <ActivityIndicator
                size="small"
                color="#fff"
                style={styles.spinner}
              />
            )}
          </TouchableOpacity>

          {connected && connectedDevice ? (
            <View style={styles.connectedDevice}>
              <Text style={styles.connectedText}>
                已连接: {connectedDevice.name}
              </Text>
              <TouchableOpacity
                style={styles.disconnectButton}
                onPress={handleDisconnectDevice}
              >
                <Text style={styles.buttonText}>断开连接</Text>
              </TouchableOpacity>
            </View>
          ) : (
            <View style={styles.deviceListContainer}>
              <Text style={styles.label}>可用设备：</Text>
              {devices.length === 0 ? (
                <Text style={styles.noDevices}>
                  {isSearching ? '正在搜索...' : '未找到设备'}
                </Text>
              ) : (
                <FlatList
                  data={devices}
                  renderItem={renderDeviceItem}
                  keyExtractor={(item) => item.id}
                  style={styles.deviceList}
                />
              )}
            </View>
          )}
        </View>

        <View style={styles.section}>
          <Text style={styles.sectionTitle}>视频播放控制</Text>
          <View style={styles.inputContainer}>
            <Text style={styles.label}>视频地址：</Text>
            <TextInput
              style={styles.input}
              value={videoUrl}
              onChangeText={setVideoUrl}
              placeholder="输入视频URL"
            />
          </View>

          <View style={styles.inputContainer}>
            <Text style={styles.label}>视频标题：</Text>
            <TextInput
              style={styles.input}
              value={videoTitle}
              onChangeText={setVideoTitle}
              placeholder="输入视频标题"
            />
          </View>

          <View style={styles.buttonGroup}>
            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={handlePlayVideo}
            >
              <Text style={styles.buttonText}>播放</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={handlePauseVideo}
            >
              <Text style={styles.buttonText}>暂停</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={handleResumeVideo}
            >
              <Text style={styles.buttonText}>恢复</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={handleStopVideo}
            >
              <Text style={styles.buttonText}>停止</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.buttonGroup}>
            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={() => handleSeek(0)}
            >
              <Text style={styles.buttonText}>跳到开始</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={() => handleSeek(30)}
            >
              <Text style={styles.buttonText}>+30秒</Text>
            </TouchableOpacity>

            <TouchableOpacity
              style={[styles.button, styles.buttonSmall]}
              onPress={handleGetStatus}
            >
              <Text style={styles.buttonText}>获取状态</Text>
            </TouchableOpacity>
          </View>

          <View style={styles.volumeContainer}>
            <Text style={styles.label}>音量 ({volume})：</Text>
            <View style={styles.volumeButtonGroup}>
              <TouchableOpacity
                style={[styles.button, styles.buttonSmall]}
                onPress={() => handleSetVolume(Math.max(0, volume - 10))}
              >
                <Text style={styles.buttonText}>-</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, styles.buttonSmall]}
                onPress={() => handleSetVolume(Math.min(100, volume + 10))}
              >
                <Text style={styles.buttonText}>+</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, styles.buttonSmall]}
                onPress={() => handleToggleMute(true)}
              >
                <Text style={styles.buttonText}>静音</Text>
              </TouchableOpacity>

              <TouchableOpacity
                style={[styles.button, styles.buttonSmall]}
                onPress={() => handleToggleMute(false)}
              >
                <Text style={styles.buttonText}>取消静音</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>

        {playbackStatus && (
          <View style={styles.section}>
            <Text style={styles.sectionTitle}>播放状态</Text>
            <View style={styles.statusContainer}>
              <Text style={styles.statusText}>
                状态: {playbackStatus.state}
              </Text>
              <Text style={styles.statusText}>
                当前位置: {Math.floor(playbackStatus.currentTime / 60)}:
                {String(Math.floor(playbackStatus.currentTime % 60)).padStart(
                  2,
                  '0'
                )}
              </Text>
              <Text style={styles.statusText}>
                总时长: {Math.floor(playbackStatus.duration / 60)}:
                {String(Math.floor(playbackStatus.duration % 60)).padStart(
                  2,
                  '0'
                )}
              </Text>
              <Text style={styles.statusText}>
                音量: {playbackStatus.volume}
              </Text>
              <Text style={styles.statusText}>
                静音: {playbackStatus.muted ? '是' : '否'}
              </Text>
            </View>
          </View>
        )}
      </ScrollView>
    </SafeAreaView>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5F5F5',
  },
  scrollView: {
    padding: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    marginBottom: 20,
    textAlign: 'center',
  },
  section: {
    backgroundColor: '#fff',
    borderRadius: 8,
    padding: 16,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    marginBottom: 12,
  },
  button: {
    backgroundColor: '#2196F3',
    padding: 12,
    borderRadius: 6,
    alignItems: 'center',
    justifyContent: 'center',
    flexDirection: 'row',
    marginVertical: 8,
  },
  buttonSmall: {
    padding: 8,
    flex: 1,
    marginHorizontal: 4,
  },
  buttonText: {
    color: '#fff',
    fontWeight: 'bold',
  },
  spinner: {
    marginLeft: 8,
  },
  deviceListContainer: {
    marginTop: 8,
  },
  deviceList: {
    maxHeight: 200,
  },
  deviceItem: {
    backgroundColor: '#E3F2FD',
    padding: 12,
    borderRadius: 6,
    marginVertical: 4,
  },
  deviceName: {
    fontWeight: 'bold',
    fontSize: 16,
  },
  deviceInfo: {
    color: '#666',
    fontSize: 12,
    marginTop: 4,
  },
  noDevices: {
    textAlign: 'center',
    color: '#666',
    marginTop: 8,
  },
  inputContainer: {
    marginBottom: 12,
  },
  label: {
    fontSize: 14,
    marginBottom: 4,
    fontWeight: '500',
  },
  input: {
    backgroundColor: '#F5F5F5',
    borderRadius: 6,
    padding: 8,
    borderWidth: 1,
    borderColor: '#ddd',
  },
  buttonGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: 8,
  },
  connectedDevice: {
    backgroundColor: '#E8F5E9',
    borderRadius: 6,
    padding: 12,
    marginTop: 8,
  },
  connectedText: {
    fontWeight: 'bold',
    marginBottom: 8,
  },
  disconnectButton: {
    backgroundColor: '#F44336',
    padding: 8,
    borderRadius: 6,
    alignItems: 'center',
  },
  statusContainer: {
    backgroundColor: '#E3F2FD',
    padding: 12,
    borderRadius: 6,
  },
  statusText: {
    marginBottom: 4,
  },
  volumeContainer: {
    marginTop: 12,
  },
  volumeButtonGroup: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  errorContainer: {
    backgroundColor: '#FFEBEE',
    padding: 12,
    borderRadius: 6,
    marginBottom: 16,
  },
  errorText: {
    color: '#D32F2F',
  },
});

export default App;
